<?php
/**
 * Created by PhpStorm.
 * User: xiaofeng
 * motto: 现在的努力是为了小时候吹过的牛逼！
 * Date: 2020/9/21
 * Time: 22:32
 */
namespace app\common\business;
use app\common\lib\Arr;
use app\common\model\mysql\Goods as GoodsModel;
use app\common\business\GoodsSku as GoodsSkuBis;
class Goods extends BusBase
{
    public $model = null;

    public function __construct()
    {
        $this->model = new GoodsModel();
    }

    public function insertData($data){
        $this->model->startTrans();
        try{
        $goodsId = $this->add($data);
        if (!$goodsId){
            return $goodsId;
        }
        // 执行数据插入到 sku表
            $goodsSkuBisobj = new GoodsSkuBis();
        // 如果是 统一规格
        if ($data['goods_specs_type'] == 1){
            $goodsSkuData = [
                "goods_id"=>$goodsId,
                "price"=>$data['price'],
                "cost_price"=>$data['cost_price'],
                "stock"=>$data['stock'],
                "status"=>1
            ];
            $goodsSkuBisobj->add($goodsSkuData);
            // 插入数据
        }elseif ($data['goods_specs_type'] == 2){ //多规格

            $data['goods_id'] = $goodsId;
            $res = $goodsSkuBisobj->saveAll($data);
            if (!empty($res)){
                $stock = array_sum(array_column($res,"stock"));
                $goodsUpdateData = [
                    'price'=>$res[0]['price'],
                    'cost_price'=>$res[0]['cost_price'],
                    'stock'=>$stock,
                    'sku_id'=>$res[0]['id']
                ];
                //执行完毕之后 更新 主表中的数据
                $goodsRes = $this->model->updateById($goodsId,$goodsUpdateData);
                if (!$goodsRes){
                    throw  new \think\Exception("insertData:goods主表更新失败");
                }
            }else{
                throw new \think\Exception("sku 表新增失败");
            }
        }
        $this->model->commit();
        }catch (\think\Exception $exception){
           $this->model->rollback();
           return false;
        }
        return true;
    }

    /**
     * 获取分类数据
     * @param $data
     * @param int $num
     * @return array
     */
    public function getList($data, $num = 5){

        $likeKeys = [];//如果没有定义这个的时候会有报错
        if (!empty($data)){
            $likeKeys = array_keys($data);
        }
        try{
            $list = $this->model->getLists($likeKeys,$data,$num);
            $result = $list->toArray();
        }catch (\Exception $exception){
            // 这个地方的结构可以写到基础类库中
            $result = Arr::getPaginateDefaultData($num);
        }
        return $result;
    }
}
